package acc;

import java.io.DataInputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

/**
 *
 * @author bjoern
 */
public class XYZConnect extends Thread {

    Callback callback = null;
    boolean running = true;

    /** Creates a new instance of XYZConnect */
    public XYZConnect(Callback callback) {
        this.callback = callback;
    }
    StringBuffer sb = new StringBuffer();

    public void run() {
        try{
            StreamConnection streamCon = (StreamConnection) Connector.open("socket://127.0.0.1:12008");
            DataInputStream is = streamCon.openDataInputStream();
            byte[] buffer = new byte[16];
            do{
                int b = is.read();
                if(b==-1){
                    break;
                }

                char c = (char)(b);
                if(c!='*'){
                    sb.append(c);
                } else {
                    String s = sb.toString();
                    sb.delete(0,sb.length());
                    String xS = s.substring(0,s.indexOf(","));
                    s=s.substring(s.indexOf(",")+1);

                    String yS = s.substring(0,s.indexOf(","));
                    s=s.substring(s.indexOf(",")+1);

                    String zS = s;

                    int x = Integer.parseInt(xS);
                    int y = Integer.parseInt(yS);
                    int z = Integer.parseInt(zS);

                    callback.callback(x,y,z);

                }

            }while(running);

            is.close();
            streamCon.close();

        }catch(Exception ee){
            ee.printStackTrace();
        }
//        while (true) {
//            callback.callback(x, x, x++);
//            try {
//                Thread.currentThread().sleep(100);
//            } catch (InterruptedException ex) {
//                ex.printStackTrace();
//            }
//        }
    }
    int x = 0;

    public void stopIt() {
        running = false;
    }
}
